package com.lsl.gulimall.product.service.impl;

import com.lsl.common.to.SkuReductionTo;
import com.lsl.common.to.SpuBoundsTo;
import com.lsl.common.utils.R;
import com.lsl.gulimall.product.entity.*;
import com.lsl.gulimall.product.feign.CouponFeignService;
import com.lsl.gulimall.product.service.*;

import com.lsl.gulimall.product.vo.request.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lsl.common.utils.PageUtils;
import com.lsl.common.utils.Query;

import com.lsl.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {


    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    SpuImagesService spuImagesService;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    CouponFeignService couponFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveInVo spuInfo) {
        //1、保存spu基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        BeanUtils.copyProperties(spuInfo, spuInfoEntity);
        this.save(spuInfoEntity);

        //2、保存Spu的描述图片 pms_spu_info_desc
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        List<String> decripts = spuInfo.getDecript();
        String decript = String.join(",", decripts);
        spuInfoDescEntity.setDecript(decript);
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);


        //3、保存spu的图片集 pms_spu_images
        List<String> spuInfoImages = spuInfo.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(), spuInfoImages);


        //4、保存spu的规格参数;pms_product_attr_value
        List<BaseAttrsInVo> attrs = spuInfo.getBaseAttrs();
        productAttrValueService.saveBaseAttrs(spuInfoEntity.getId(), attrs);


        //5、保存spu的积分信息；gulimall_sms->sms_spu_bounds
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        spuBoundsTo.setSpuId(spuInfoEntity.getId());
        BeanUtils.copyProperties(spuInfo.getBounds(), spuBoundsTo);
        R r = couponFeignService.saveSpuBounds(spuBoundsTo);
        if (r.getCode() != 0) {
            log.error("远程保存spu积分信息失败");
        }

        //5、保存当前spu对应的所有sku信息；
        List<SkusInVo> skusInVos = spuInfo.getSkus();
        if (skusInVos != null && skusInVos.size() > 0) {
            SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
            for (SkusInVo skusInVo : skusInVos) {
                String defaultImage = "";
                List<ImagesInVo> images = skusInVo.getImages();

                if (images != null && images.size() > 0) {
                    for (ImagesInVo imagesInVo : images) {
                        if (imagesInVo.getDefaultImg() == 1) {
                            defaultImage = imagesInVo.getImgUrl();
                        }
                    }
                }
                BeanUtils.copyProperties(skusInVo, skuInfoEntity);
                skuInfoEntity.setSkuDefaultImg(defaultImage);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setBrandId(spuInfo.getBrandId());
                skuInfoEntity.setCatalogId(spuInfo.getCatalogId());
                skuInfoEntity.setSaleCount(0L);

                //5.1）、sku的基本信息；pms_sku_info
                skuInfoService.save(skuInfoEntity);
                //5.2）、sku的图片信息；pms_sku_image
                Long skuId = skuInfoEntity.getSkuId();
                List<SkuImagesEntity> skuImagesEntities = images.stream().map(
                        (image) -> {
                            SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                            skuImagesEntity.setSkuId(skuId);
                            skuImagesEntity.setImgUrl(image.getImgUrl());
                            skuImagesEntity.setDefaultImg(image.getDefaultImg());
                            return skuImagesEntity;
                        }).filter((item) -> StringUtils.isNotEmpty(item.getImgUrl()))
                        .collect(Collectors.toList());
                skuImagesService.saveBatch(skuImagesEntities);

                //5.3）、sku的销售属性信息：pms_sku_sale_attr_value
                List<AttrVo> attrVos = skusInVo.getAttr();
                List<ProductAttrValueEntity> productAttrValueEntityList = attrVos.stream().map(
                        (attr) ->
                        {
                            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
                            BeanUtils.copyProperties(attr, productAttrValueEntity);
                            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
                            return productAttrValueEntity;
                        }
                ).collect(Collectors.toList());
                productAttrValueService.saveBatch(productAttrValueEntityList);

                //5.4）、sku的优惠、满减等信息；gulimall_sms->sms_sku_ladder\sms_sku_full_reduction\sms_member_price
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(skusInVo, skuReductionTo);
                skuReductionTo.setSkuId(skuInfoEntity.getSkuId());

                if (skusInVo.getFullCount() > 0 && skusInVo.getFullPrice().compareTo(new BigDecimal(0)) == 1) {
                    R r1 = couponFeignService.saveSkuFullReduction(skuReductionTo);
                    if (r1.getCode() != 0) {
                        log.error("远程保存sku优惠信息失败");
                    }
                }
            }
        }
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        String key = (String) params.get("key");
        String status = (String) params.get("status");
        String brandId = (String) params.get("brandId");
        String catelogId = (String) params.get("catelogId");
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(key)){
           queryWrapper.and((wrapper)->{
                wrapper.eq("id",key).or().like("spu_name",key);
           });
        }
        if(StringUtils.isNotEmpty(status)){
           queryWrapper.eq("publish_status",status);
        }
        if(StringUtils.isNotEmpty(brandId) && !"0".equalsIgnoreCase(brandId)){
          queryWrapper.eq("brand_id",brandId);
        }
        if(StringUtils.isNotEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)){
            queryWrapper.eq("catalog_id",catelogId);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }
}